<?php


namespace App\Repositories;


use App\Enums\RedisKeyEnum;
use App\Exceptions\BasicException;
use Illuminate\Support\Facades\DB;

class CustomerServiceQuestionRepository
{
    //新增或编辑客服问题
    public function addOrEdit($param)
    {
        $id = $param['id'] ?? 0;
        $questionName = $param['question_name'];
        $questionNameKeyword = $param['question_name_keyword'];
        $questionAnswer = $param['question_answer'];
        $sort = $param['sort'];
        $validDateType = $param['valid_date_type'];
        $validDateStart = $param['valid_date_start'] ?? '';
        $validDateEnd = $param['valid_date_end'] ?? '';
        $status = $param['status'];
        $remark = $param['remark'] ?? '';

        if ($id > 0) {
            $question = app('model_customer_service_question')->select('id', 'name')->where('id', $id)->first();
            if (empty($question)) throw new BasicException(0, '参数错误，问题不存在');
        }
        $questionNameKeywordArr = explode('，', $questionNameKeyword);
        if (count($questionNameKeywordArr) < 2 || count($questionNameKeywordArr) > 10) {
            throw new BasicException(0, '请设置2-10个关键词');
        }
        foreach ($questionNameKeywordArr as $v) {
            if (mb_strlen($v) > 6) throw new BasicException(0, '每个关键词的长度不能超过6');
        }
        if (strpos($questionNameKeyword, ',') !== false) {
            throw new BasicException(0, '关键词之间请用中文逗号隔开');
        }

        $exist = app('model_customer_service_question')->select('id')
            ->where('name', $questionName)
            ->where(function ($query) use ($id) {
                if ($id > 0) {
                    $query->where('id', '<>', $id);
                }
            })->first();
        if ($exist) throw new BasicException(0, '问题名称已经存在');

        //新增客服问题
        $data = [
            'name' => $questionName,
            'answer' => $questionAnswer,
            'keywords' => $questionNameKeyword,
            'sort' => $sort,
            'remark' => $remark,
            'status' => $status,
        ];
        if ($validDateType == 1) {
            $data['start_time'] = time();
            $data['end_time'] = -1;
        } else {
            $data['start_time'] = strtotime($validDateStart . ' 0:0:0');
            $data['end_time'] = strtotime($validDateEnd . ' 23:59:59');
        }

        DB::beginTransaction();
        try {
            if ($id > 0) {

                //更新客服问题
                app('model_customer_service_question')->where('id', $id)->update($data);

                //删除原关键词与问题id关联
                $originalKeywords = $this->splitWord($question->name);
                foreach ($originalKeywords as $originalKeyword) {
                    $questionKeyword = app('model_customer_service_question_keywords')->select('id', 'question_ids')->where('keyword', $originalKeyword)->first();
                    $questionKeywordArr = explode(',', trim($questionKeyword->question_ids, ','));
                    if ($key = array_search($id, $questionKeywordArr) !== false) {
                        unset($questionKeywordArr[$key]);
                    }
                    app('model_customer_service_question_keywords')
                        ->where('id', $questionKeyword->id)
                        ->update(['question_ids' => ',' . implode(',', $questionKeywordArr) . ',']);
                }
            } else {
                //新增客服问题
                $id = app('model_customer_service_question')->insertGetId($data);
            }

            //更新关键词与问题id关联
            $this->updateKeywordQuestionId($questionNameKeywordArr, $id);

            DB::commit();

            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, $e->getMessage());
        }
    }

    //分词
    public function splitWord($content, $minWordLen = 2, $maxWordLen = 5)
    {
        $baseSplitWords = app('model_customer_service_question_keywords')
            ->select('id', 'keyword')->pluck('id', 'keyword');
        $baseSplitWords = json_decode($baseSplitWords, true);

        //无差别分词
        $contentLen = mb_strlen($content);
        $splitWords = [];
        for ($i = 0; $i < $contentLen; $i++) {
            for ($wordLen = $minWordLen; $wordLen <= $maxWordLen; $wordLen++) {
                $word = mb_substr($content, $i, $wordLen);
                if (mb_strlen($word) < $wordLen) {
                    break;
                } else {
                    $splitWords[] = $word;
                }
            }
        }

        //提取有效分词（在分词库中）
        $validSplitWords = [];
        foreach ($splitWords as $splitWord) {
            if (isset($baseSplitWords[$splitWord])) {
                $validSplitWords[] = $splitWord;
            }
        }

        return $validSplitWords;
    }

    /**
     * 更新客服问题id
     * @param array $keywords 关键词
     * @param int $questionId 问题id
     */
    private function updateKeywordQuestionId($keywords, $questionId)
    {
        foreach ($keywords as $keyword) {
            $questionWord = app('model_customer_service_question_keywords')
                ->select('id', 'question_ids')
                ->where('keyword', $keyword)->first();

            if ($questionWord) {

                $questionIdArr = explode(',', trim($questionWord->question_ids, ','));
                if (!in_array($questionId, $questionIdArr)) {
                    $questionIdArr[] = $questionId;
                }

                app('model_customer_service_question_keywords')
                    ->where('id', $questionWord->id)->update(['question_ids' => ',' . implode(',', $questionIdArr) . ',']);

            } else {

                app('model_customer_service_question_keywords')->insert([
                    'keyword' => $keyword,
                    'question_ids' => ',' . $questionId . ',',
                ]);
            }
        }
    }
}